package com.ftg.learn.day10;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 学习线程
 * Lock
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/8/7 下午3:01
 */
public class LearnThread02 {

    private static int person_no = 0;

//    ReentrantLock  可重入锁

    static Lock lock = new ReentrantLock();

    private static void addPersonNo() {
        //上锁

        //异常 ( try catch finally )
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "==>" + person_no++);
        }catch (Exception e){
            System.out.println("当try里面出现 异常的时候  ");
        }finally {
            //
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                addPersonNo();
            }
        });
        t1.setName("第一个线程");

        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                addPersonNo();
            }
        });

        t2.setName("第二个线程");

        t2.start();


        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("最终结果 ==> " + person_no);

    }

    // 1 : 多线程下面的题   厨子 (面包)  销售员.... (只能有一个面包)


    // 2 : 多线程下面的题   厨子 (面包柜台 5个 )  销售员....

}
